package bagdao

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"xr-game-server/core/cache"
	"xr-game-server/core/constants/common"
	"xr-game-server/entity"
)

var bagCache *cache.CacheMgr

// GetBagCells 从缓存中拉取道具表 ttl 30分钟 缓存为空 从数据库拉取
func GetBagCells(roleId uint64) []*entity.PlayerBag {
	cacheData := bagCache.GetData(roleId, func(ctx context.Context) (value interface{}, err error) {
		items := make([]*entity.PlayerBag, common.Zero)
		g.Model(string(entity.TbPlayerBag)).Unscoped().Where(string(entity.PlayerBagRoleId), roleId).Scan(&items)
		return items, nil
	})
	return cacheData.([]*entity.PlayerBag)
}

func GetBagCell(roleId uint64, itemId uint64) *entity.PlayerBag {
	cacheData := GetBagCells(roleId)
	for _, item := range cacheData {
		if item.CfgId == itemId {
			return item
		}
	}
	return nil
}

func AddToCache(roleId uint64, cell *entity.PlayerBag) {
	cacheData := GetBagCells(roleId)
	cacheData = append(cacheData, cell)
	bagCache.FlushCache(roleId, cacheData)
}

func InitBagDao() {
	bagCache = cache.NewCacheMgr()
}
